<template>
  <div style="display: flex" :class="{ navMenuState: navMenuState }" class="monitor">
    <ul class="left_list">
      <li v-show="monitorSummaryShow">
        <h3 class="min_title">
          {{ $t('monitor.monitorSummary') }}
        </h3>
        <p v-if="flag === 'kf'" @click="tab('CallSummary')" :class="activeComponent === 'CallSummary' ? 'active' : ''">
          {{ $t('public.phoneNum') }}
        </p>
        <p @click="tab('WebchatSummary')" :class="activeComponent === 'WebchatSummary' ? 'active' : ''">
          {{ $t('login.onLineServer') }}
        </p>
      </li>
      <li>
        <h3 class="min_title">
          {{ $t('monitor.monitorDetail') }}
        </h3>
        <p
          v-if="flag === 'kf'"
          @click="tab('MonitorTable')"
          :class="activeComponent === 'MonitorTable' ? 'active' : ''"
        >
          {{ $t('monitor.table') }}
        </p>
        <p @click="tab('MonitorTableIm')" :class="activeComponent === 'MonitorTableIm' ? 'active' : ''">
          {{ $t('monitor.tableIm') }}
        </p>
        <p @click="tab('OrderMonitorTable')" :class="activeComponent === 'OrderMonitorTable' ? 'active' : ''">
          {{ $t('monitor.tableOrder') }}
        </p>
        <!--<p @click="tab('MonitorRemoteControl')" :class="activeComponent === 'MonitorRemoteControl'? 'active': ''">{{$t('monitor.remoteControl')}}</p>-->
      </li>
      <li>
        <h3 class="min_title">
          {{ $t('monitor.cdrpeer') }}
        </h3>
        <p
          v-if="flag === 'kf'"
          @click="tab('MonitorCdrpeer')"
          :class="activeComponent === 'MonitorCdrpeer' ? 'active' : ''"
        >
          {{ $t('monitor.callAgentLog') }}
        </p>
        <p @click="tab('MonitorCdrpeerIm')" :class="activeComponent === 'MonitorCdrpeerIm' ? 'active' : ''">
          {{ $t('monitor.chatAgentLog') }}
        </p>
      </li>
    </ul>
    <div class="summary">
      <keep-alive>
        <component :is="activeComponent"></component>
      </keep-alive>
    </div>
  </div>
</template>
<script>
//  import MonitorTemp from './MonitorTableTemp.vue'
//  import MonitorTable from './MonitorTableNew.vue'
//  import MonitorChart from './MonitorChart.vue'
//  import MonitorCdrpeer from './MonitorCdrpeer.vue'
//  import TableOption from './TableOption.vue'
//  import MonitorTempIm from './MonitorTableTempIm.vue'
//  import MonitorTableIm from './MonitorTableIm.vue'
import { isHasMenu, checkHideTel, getFormatDateTime, contains } from '@/utils/m7Utils.js'
import { ctiUicontrolMonitor, ctiUiDisplayStatus, ctiUiDisplayExtenType } from '@/utils/monitor.js'
import { addZhuGeTrack } from '@/utils/addZhuGeTrack.js'
import bus from '@/store/eventBus'
export default {
  name: 'monitor',
  data() {
    return {
      flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
      licenceType: {},
      activeName: '',
      loading: true,
      addOptions: false,
      firstIn: false,
      currentRoute: '',
      activeComponent: '',
      menu: [
        { name: 'MonitorSummary', label: this.$t('monitor.monitorSummary'), fun: 'monitor_platform' },
        { name: 'MonitorTable', label: this.$t('monitor.table'), fun: 'monitor_platform' },
        { name: 'MonitorTableIm', label: this.$t('monitor.tableIm'), fun: 'monitor_platform' },
        { name: 'orderMonitorTable', label: this.$t('monitor.tableOrder'), fun: 'monitor_platform' },
        { name: 'MonitorCdrpeer', label: this.$t('monitor.cdrpeer'), fun: 'monitor_log_record' },
        { name: 'MonitorRemoteControl', label: this.$t('monitor.remoteControl'), fun: 'monitor_remote_assist' }
      ],
      options: [],
      filterData: {},
      webchat: {
        peers: {},
        queues: {},
        serviceNums: {}
      },
      peersDetail: {},
      phone: {
        peers: {},
        queues: {},
        serviceNums: {}
      },
      summaryCall: {
        waitCountTotal: 0, // 技能组排队数
        dailinTime: 0,
        dailoutTime: 0,
        queueData: 0, // 账户下排队数
        incomingData: 0, // 账户呼入量
        agents: {},
        allLicece: 0
      },
      commonData: {
        time: ''
      },
      initType: [],
      monitorSummaryShow: true,
      agentType: this.$store.state.session.user.type
    }
  },
  components: {
    MonitorRemoteControl: () => import('../monitor.old/MonitorRemoteControl.vue'),
    MonitorTable: () => import('./callMonitor.vue'),
    MonitorTableIm: () => import('./webchatMonitor.vue'),
    CallSummary: () => import('./callSummary.vue'),
    WebchatSummary: () => import('./webchatSummary.vue'),
    MonitorCdrpeer: () => import('./monitorCdrpeer.vue'),
    MonitorCdrpeerIm: () => import('./monitorCdrpeerIm.vue'),
    TableOption: () => import('./option.vue'),
    OrderMonitorTable: () => import('./orderMonitorTable.vue')
  },
  computed: {
    navMenuState() {
      return this.$store.state.navMenuState || false
    },
    heartBeat() {
      let pbx = this.$store.state.session.user.pbx
      let data = this.$store.state.monitor.table.phone_heartBeat[pbx]
      return data
    }
  },
  created() {
    //      this.$router.push({ path: '/index/monitor/table' })
  },
  methods: {
    // 监控权限判断
    isMenu(flag) {
      this.menu = this.menu.filter((item) => {
        return !item.fun || (item.fun && isHasMenu(item.fun, this.$store.state.session.user))
      })
      console.log(this.activeName)
      if (!flag) {
        this.activeName = this.menu[0].name
        this.tab(this.menu[0])
      }
      //        this.$router.push({ path: '/index/monitor/' + this.activeName })
    },
    // tab菜单切换
    tab(index, event) {
      this.activeComponent = index
      let tabName = `/index/monitorNew/${index}`
      addZhuGeTrack(tabName)
    },
    update(target, data) {
      for (const key in data) {
        if (key in target) {
          target[key] = data[key]
        } else {
          this.$set(target, key, data[key])
        }
      }
    },
    // 初始化各个部分，如果已经初始化直接return
    init(type) {
      let self = this
      if (this.initType.indexOf(type) !== -1) {
        return
      }
      this.initType.push(type)
      return self[type]()
    },
    // 处理在线咨询坐席数据
    webchatPeersData() {
      let data = Object.keys(this.$store.state.monitor.table.agentMonitor)
      data.forEach((item) => {
        if (this.webchat.peers[item]) {
          this.webchat.peers[item] = this.monitorPeerNewIm(this.$store.state.monitor.table.agentMonitor[item], item)
        } else {
          this.$set(
            this.webchat.peers,
            item,
            this.monitorPeerNewIm(this.$store.state.monitor.table.agentMonitor[item], item)
          )
        }
      })
    },
    // 初始化在线咨询坐席详情
    webchatInit() {
      if (this.$store.state.monitor.moduleOpen.webchat) {
        // 有数据直接使用，不发请求
        this.webchatPeersData()
        // 数据渲染完后刷新trAgentIm组件
        this.$nextTick(() => {
          bus.$emit('monitor:imMonitorRefresh')
        })
      } else {
        let p1 = this.$store.dispatch('imMonitorInit', {})
        let p2 = this.$store.dispatch('getCache', { type: 'mailQueues' })
        this.$store.commit('monitor/MONITOR_MODULE_OPEN', { type: 'webchat', status: true })
        Promise.all([p1, p2]).then(() => {
          this.webchatPeersData()
          // 数据渲染完后刷新trAgentIm组件
          this.$nextTick(() => {
            bus.$emit('monitor:imMonitorRefresh')
          })
          return true
        })
      }
    },
    // 初始化通话坐席详情
    phonePeersInit(arr) {
      let p1 = this.$store.dispatch('getCache', { type: 'phoneBars' })
      // 获取各版本的licence
      let p2 = this.$store.dispatch('queryVersionNum', { pbx: this.$store.state.session.user.pbx })
      Promise.all([p1, p2]).then(([res1, res2]) => {
        // 初始化饼图数据
        let statusCount = {
          unregister: { name: this.$t('cti.unlink'), value: 0, members: [] },
          offline: { name: this.$t('cti.offline'), value: 0 },
          ready: { name: this.$t('cti.ready'), value: 0 },
          calling: { name: this.$t('monitor.calling1'), value: 0, members: [] }
        }
        res1.forEach((item) => {
          if (item.IsEnable === '1') {
            statusCount[item.PhoneBarItemId] = { name: item.PhoneBarItemName, value: 0, members: [] }
          }
        })
        this.$set(this.summaryCall, 'agents', statusCount)
        // 初始化lisence数据
        if (res2 && res2.success) {
          let response = res2.uversions || []
          let Packages = this.$getCache('licenceType')
          for (let i in response) {
            for (let j = 0; j < Packages.length; j++) {
              if (response[i]._id === Packages[j].code_value) {
                this.$set(this.licenceType, Packages[j].code_value, {
                  label: Packages[j].code_name,
                  key: Packages[j].code_value,
                  online: 0,
                  offline: 0, // 离线接听数
                  value1: response[i].brrowLicenceCount || 0
                })
                this.summaryCall.allLicece += response[i].licenceCount
                // this.licenceType.push({
                //   label: Packages[j].code_name,
                //   key: Packages[j].code_value,
                //   online: 0,
                //   value1: response[i].licenceCount
                // })
              }
            }
          }
        }
        let data = arr || Object.keys(window.phone_peers)
        let flag = arr ? '' : 'create'
        data.forEach((item) => {
          this.$set(this.phone.peers, item, this.monitorPeerNew(window.phone_peers[item], flag, item))
          this.statusChange(this.phone.peers[item], 'plus')
          let peer = this.phone.peers[item]
          // 按版本统计离线接听和在线坐席数
          this.versionChange(null, peer)
        })
        // 数据渲染完后刷新trAgentIm组件
        this.$nextTick(() => {
          bus.$emit('monitor:callMonitorRefresh')
        })
      })
    },
    // 通话坐席数据处理
    monitorPeerNew(phone, flag, user) {
      let ctiUiDesc = this.$store.state.cti.globalLet._cti_ui_desc // 获取通话各状态描述
      let phoneData = this.$store.state.cti.globalLet.phone_data // 获取空闲各状态描述
      let onePeer = phone
      if (!onePeer) {
        return {}
      }
      let agentName = onePeer.DisplayName ? onePeer.DisplayName : ''
      // userId取key值，防止两个座席绑定同一个sipNum时，一直push的问题
      let userId = user
      let agentNo = onePeer.exten
      let answerStyle = ctiUiDisplayExtenType(onePeer) // 当前坐席接听方式
      let state = ctiUiDisplayStatus(onePeer, ctiUiDesc, phoneData) // 当前坐席状态
      var date = new Date()
      let statusTime = onePeer.statusTime || {}
      let timeDiff = onePeer.statusTimestamp ? date.getTime() - onePeer.statusTimestamp : 0 // 获取当前时间与最近一次更新的时间差
      // 总置忙时长
      let allBusyTime = Number(statusTime.AllBusyTime) || 0
      // 总小休时长
      let allVacaTime = Number(statusTime.AllVacaTime) || 0
      // 总在线时长
      let allOnlineTime = Number(statusTime.AllOnlineTime) || 0
      // 总空闲时长
      let allIdleTime = Number(statusTime.AllIdleTime) || 0
      let busyNum = statusTime.BusyNum || 0
      let vacaNum = statusTime.VacaNum || 0
      if (onePeer.login) {
        if (onePeer.busyType !== '0' && onePeer.busyType !== '2') {
          // 忙碌
          allBusyTime += timeDiff
        }
        if (onePeer.busyType === '2') {
          // 小休
          allVacaTime += timeDiff
        }
        if (onePeer.login) {
          // 在线
          allOnlineTime += timeDiff
        }
        if (onePeer.busyType === '0') {
          // 空闲
          allIdleTime += timeDiff
        }
      }
      let dealingTime = onePeer.DialoutTimeLength
      let dealingInTime = onePeer.DialinTimeLength
      let queueName = onePeer.queueName ? onePeer.queueName : ''
      let customerNo = checkHideTel(onePeer.callNo, this.$store.state.session.user)
      let answerCount = onePeer.InComplete
      let dealingSuccessCount = onePeer.OutComplete
      let buttonState = ctiUicontrolMonitor(onePeer, phoneData, this.$store.state) || {} // 操纵按钮是否disabled
      let operate = {
        channel: onePeer.channel,
        userId: userId,
        pbx: onePeer.pbx,
        linkedChannel: onePeer.linkedChannel,
        buttonState: buttonState
      }
      let stateTime = ''
      let condition = (onePeer.login || onePeer.rserve) && onePeer.timestamp
      if (flag !== 'create') {
        condition = onePeer.extenType && onePeer.timestamp
      }
      if (condition) {
        // 如果登陆系统，记录状态时长
        var identity = date.valueOf()
        var oldTime = identity - phoneData.currentServerTime - parseFloat(onePeer.timestamp) * 1000
        if (oldTime < 0) {
          oldTime = 0
        }
        stateTime = oldTime
      } else {
      }
      return {
        userId: userId,
        register: onePeer.register,
        login: onePeer.login,
        busyType: onePeer.busyType,
        allBusyTime,
        allVacaTime,
        allOnlineTime,
        allIdleTime,
        busyNum,
        vacaNum,
        DealingTime: dealingTime,
        dealingInTime,
        agentName,
        agentNo,
        answerStyle,
        state,
        stateTime,
        dealingTime,
        queueName,
        customerNo,
        answerCount,
        dealingSuccessCount,
        inCalls: onePeer.InCalls,
        outCalls: onePeer.OutCalls,
        operate,
        version: onePeer.version,
        extenType: onePeer.extenType,
        sensitiveWord: onePeer.sensitive || '',
        sensitiveAgent: onePeer.sensitiveAgent || '',
        sensitiveCustomer: onePeer.sensitiveCustomer || ''
      }
    },
    // 通话坐席状态改变, 处理对应状态数量
    statusChange(peer, type) {
      if (!peer) {
        return
      }
      let state = peer.state.state
      let agentsState = this.summaryCall.agents[state]
      if (state && agentsState) {
        if (type === 'plus') {
          agentsState.value++
          // if (agentsState.members) {
          //   agentsState.members.push(peer._id)
          // }
        } else if (type === 'minus') {
          agentsState.value--
          // if (agentsState.members) {
          //   let index = agentsState.members.indexOf(peer._id)
          //   agentsState.members.splice(index, 1)
          // }
        }
      }
      if (type === 'plus') {
        this.summaryCall.dailinTime += peer.dealingInTime || 0
        this.summaryCall.dailoutTime += peer.dealingTime || 0
      } else if (type === 'minus') {
        this.summaryCall.dailinTime -= peer.dealingInTime || 0
        this.summaryCall.dailoutTime -= peer.dealingTime || 0
      }
    },
    monitorPeerNewIm(im, user) {
      let item = im
      let agentName = item.displayName ? item.displayName : ''
      // userId取key值，防止两个座席绑定同一个sipNum时，一直push的问题
      let userId = user
      let agentNo = item.exten
      let pcState = item.pcState ? 1 : 0
      let mobileState = item.mobileState ? 1 : 0
      let pcAutoStatus = item.pcAutoClaim ? 1 : 0
      let mobileAutoStatus = item.mobileAutoClaim ? 1 : 0
      let mailAutoStatus = item.mailAutoClaim ? 1 : 0
      let customizeStatus = item.pcToggleNew
      let mobileClaimTime = ''
      let currtenTime = new Date().getTime()
      if (item.mobileClaimTime) {
        mobileClaimTime = currtenTime - item.mobileClaimTime
      }
      let pcClaimTime = ''
      if (item.pcClaimTime) {
        pcClaimTime = currtenTime - item.pcClaimTime
      }
      let closestTime = ''
      //  pcClaimState 值为 'open' 'close' '1' '2' '3' '4' '5'
      if (item.pcClaimState && item.pcCloseClaimTime > 0) {
        closestTime = currtenTime - item.pcCloseClaimTime
      }
      let autoOrderInitStatus = item.autoOrderInitStatus === 'busy' ? 'busy' : 'order'
      let sessionTotalTime1 = item.pcClaimState === '1' ? closestTime : '' // 自定义状态1
      let sessionTotalTime2 = item.pcClaimState === '2' ? closestTime : '' // 自定义状态2
      let sessionTotalTime3 = item.pcClaimState === '3' ? closestTime : '' // 自定义状态3
      let sessionTotalTime4 = item.pcClaimState === '4' ? closestTime : '' // 自定义状态4
      let sessionTotalTime5 = item.pcClaimState === '5' ? closestTime : '' // 自定义状态5
      let closeSessionTotalTime = item.pcClaimState === 'close' ? closestTime : '' // 忙碌状态
      // 移动端停用状态时长计算
      // let mobileCloseClaimTime = ''
      // if (mobileState === 0) {
      //   mobileCloseClaimTime = item.mobileCloseClaimTime
      // }
      //        let autoStatus = this.$t(renderAutoClaimDispaly(item.autoClaim))
      let imDealCount = item.imDealCount || ''
      let currentSessionCount = item.dealing ? item.dealing : 0
      let sessionAccessCount = item.claim ? item.claim : 0
      let sessionRollInCount = item.sessionRollInCount ? item.sessionRollInCount : 0
      let sessionRollOutCount = item.sessionRollOutCount ? item.sessionRollOutCount : 0
      let sessionCompleteCount = item.sessionCompleteCount ? item.sessionCompleteCount : 0
      let agentInviteCount = item.agentInviteCount ? item.agentInviteCount : 0
      let inviteSessionCount = item.invitsession ? item.invitsession : 0
      return {
        userId: userId,
        agentState: item.agentState,
        agentName,
        agentNo,
        pcState,
        mobileState,
        pcAutoStatus,
        mobileAutoStatus,
        pcClaimTime,
        mobileClaimTime,
        imDealCount,
        sessionRollInCount,
        sessionRollOutCount,
        sessionCompleteCount,
        agentInviteCount,
        sessionAccessCount,
        inviteSessionCount,
        currentSessionCount,
        mailAutoStatus,
        customizeStatus,
        autoOrderInitStatus,
        closeSessionTotalTime,
        sessionTotalTime1,
        sessionTotalTime2,
        sessionTotalTime3,
        sessionTotalTime4,
        sessionTotalTime5
      }
    },
    queuesMemberSort(data) {
      let count = { callingAgentCount: 0, busyAgentCount: 0 }
      // Object.keys(data.members).forEach((item) => {
      //   let peersSip = window._phone_peersFromSip[item]
      //   if (peersSip) {
      //     let userId = peersSip.userId
      //     let state = this.phone.peers[userId].state || {}
      //     if (state.state === 'calling') {
      //       count.callingAgentCount++
      //     } else if (state.state >= 1) {
      //       count.busyAgentCount ++
      //     }
      //   }
      // })
      return count
    },
    // 通话技能组初始化及更新
    phoneQueuesInit(arr) {
      let data = window.phone_queues
      let waitCountTotal = 0
      for (var i in data) {
        var data1 = {}
        // {prop: 'totalAgentCount', tooltip: true},
        // {prop: 'idleAgentCount', tooltip: true},
        // {prop: 'callingAgentCount', tooltip: true},
        // {prop: 'busyAgentCount', tooltip: true},
        // {prop: 'queueWaitCount', color: 'red'},
        // {prop: 'abadonedCalls'},
        // {prop: 'linkCalls'}]
        waitCountTotal += data[i].queueWaitCount
        // if (data[i].totalAgentCount !== 0) {
        //   data1.totalAgentCount = data1.totalAgentCount + ctiUiGetQueuePeer(data[i], this.$store.state)
        // }
        data1.totalAgentCount = data[i].totalAgentCount
        data1.idleAgentCount = data[i].idleAgentCount
        data1.queueWaitCount = data[i].queueWaitCount
        data1.callingAgentCount = data[i].callUserCount
        data1.busyStateAgentCount = data[i].busyAgentCount + data[i].unregisterCount
        data1.abadonedCalls = data[i].abadonedCalls
        data1.queueAbandon = data[i].queueAbandon || 0
        data1.serviceLevel = data[i].ServiceQuality || '0.00'
        let linkCalls = data[i].totalCalls - data[i].abadonedCalls
        data1.linkCalls = linkCalls > 0 ? linkCalls : 0
        data1.queueId = i
        data1.queueName = data[i].queueName
        data1.members = data[i].members
        if (this.phone.queues[i]) {
          this.update(this.phone.queues[i], data1)
        } else {
          this.$set(this.phone.queues, i, data1)
        }
        this.summaryCall.waitCountTotal = waitCountTotal
      }
    },
    // 通话服务号初始化及更新
    phoneserviceNumsInit(arr) {
      let data = window.phone_serviceNos
      for (let i in data) {
        if (data[i].displayName !== '') {
          data[i].serviceNoName = data[i].serviceNo + '(' + data[i].displayName + ')'
        } else {
          data[i].serviceNoName = data[i].serviceNo
        }
        if (this.phone.serviceNums[i]) {
          this.update(this.phone.serviceNums[i], data[i])
        } else {
          this.$set(this.phone.serviceNums, i, data[i])
        }
      }
    },
    // 坐席状态时长，时间的定时器
    timeChange() {
      let self = this
      this.timer = window.setInterval(function () {
        self.commonData.time = getFormatDateTime(new Date(), 'monitor')
        for (let i in self.phone.peers) {
          let onePeer = self.phone.peers[i]
          if (onePeer.stateTime !== '') {
            onePeer.stateTime += 1000
          }
          if (onePeer.login) {
            // 在线
            onePeer.allOnlineTime += 1000
            if (onePeer.register) {
              if (onePeer.busyType !== '0' && onePeer.busyType !== '2') {
                // 忙碌
                onePeer.allBusyTime += 1000
              }
              if (onePeer.busyType === '2') {
                // 小休
                onePeer.allVacaTime += 1000
              }
              if (onePeer.busyType === '0') {
                // 空闲
                onePeer.allIdleTime += 1000
              }
            }
          }
        }
        for (let i in self.webchat.peers) {
          let onePeer = self.webchat.peers[i]
          if (onePeer.pcClaimTime !== '') {
            onePeer.pcClaimTime += 1000
          }
          if (onePeer.mobileClaimTime !== '') {
            onePeer.mobileClaimTime += 1000
          }
          if (onePeer.closeSessionTotalTime !== '') {
            onePeer.closeSessionTotalTime += 1000
          }
          if (onePeer.sessionTotalTime1 !== '') {
            onePeer.sessionTotalTime1 += 1000
          }
          if (onePeer.sessionTotalTime2 !== '') {
            onePeer.sessionTotalTime2 += 1000
          }
          if (onePeer.sessionTotalTime3 !== '') {
            onePeer.sessionTotalTime3 += 1000
          }
          if (onePeer.sessionTotalTime4 !== '') {
            onePeer.sessionTotalTime4 += 1000
          }
          if (onePeer.sessionTotalTime5 !== '') {
            onePeer.sessionTotalTime5 += 1000
          }
        }
      }, 1000)
    },
    // 判断监控数据权限，noScope为全部
    scopeAgents(type) {
      let session = this.$store.state.session
      if (session.user.type !== 'admin' && session.user.scope[type] !== 'all') {
        let lowUsers = session.user.moduleUsers[type] || []
        return lowUsers
      } else {
        return 'noScope'
      }
    },
    // 页面进入是的初始化
    initData() {
      let p1 = this.$store.dispatch('initHeartBeat', { current: true }) // 获取当前排队数和呼入数
      let p2 = this.$store.dispatch('getConcurrent') // 获取当前排队数和呼入数
      Promise.all([p1, p2]).then(([res1, res2]) => {
        // this.summaryCall.queueData = res1.ctQueueData
        this.summaryCall.incomingData = res1.ctIncomingData
      })
    },
    // 处理licence版本登陆坐席的数量
    versionChange(before, now) {
      now = now || {}
      let version = now.version
      if (!this.licenceType[version]) {
        return
      }
      if (before) {
        if (before.login === now.login) {
        } else if (before.login === true && now.login === false) {
          this.licenceType[version].online--
        } else if (before.login === false && now.login === true) {
          this.licenceType[version].online++
        }
        this.licenceType[version].offline += this.offlineCompare(before, now)
      } else {
        if (now.login === true && this.licenceType[version]) {
          this.licenceType[version].online++
        } else if (this.offline(now)) {
          this.licenceType[version].offline++
        }
      }
    },
    offline(peer) {
      let state = peer.state || {}
      if (state.state === 'offline') {
        console.log(peer.login + '  ' + peer.agentNo + '   ' + peer.version + '  ' + peer.extenType)
        return true
      }
      return false
    },
    offlineCompare(before, now) {
      let beforeOffline = this.offline(before)
      let nowOffline = this.offline(now)
      if (beforeOffline === nowOffline) {
        return 0
      } else if (beforeOffline !== nowOffline) {
        return nowOffline ? 1 : -1
      }
    }
  },
  watch: {
    '$store.state.cti.serviceNoChange.random'() {
      if (this.agentType === 'agent') {
        return
      }
      this.phoneserviceNumsInit()
    },
    '$store.state.cti.phoneQueuesChange.random'() {
      if (this.agentType === 'agent') {
        return
      }
      this.phoneQueuesInit()
    },
    '$store.state.monitor.agentStateChange.random'() {
      if (this.agentType === 'agent') {
        return
      }
      let newValue = this.$store.state.monitor.agentStateChange.userIdNew
      for (let i in newValue) {
        let newV = newValue[i]
        if (this.phone.peers[newV]) {
          let peer = this.monitorPeerNew(window.phone_peers[newV], 'update', newV)
          this.versionChange(this.phone.peers[newV], peer)
          this.statusChange(this.phone.peers[newV], 'minus')
          this.update(this.phone.peers[newV], peer)
          // this.phone.peers[newV] = this.monitorPeerNew(window.phone_peers[newV], 'update', newV)
          this.statusChange(this.phone.peers[newV], 'plus')
        } else {
          this.$set(this.phone.peers, newV, this.monitorPeerNew(window.phone_peers[newV], 'update', newV))
          this.statusChange(this.phone.peers[newV], 'plus')
          this.versionChange(null, this.phone.peers[newV])
        }
      }
      bus.$emit('monitor:agentChange', newValue)
      this.$store.commit('AGENT_STATE_CHANGE', 'deleteNew')
    },
    '$store.state.monitor.agentStateChangeIm.random'(newValue) {
      let im = this.$store.state.monitor.table.agentMonitor
      let newV = this.$store.state.monitor.agentStateChangeIm.userId
      if (this.webchat.peers[newV]) {
        this.update(this.webchat.peers[newV], this.monitorPeerNewIm(im[newV], newV))
        // this.webchat.peers[newV] = this.monitorPeerNewIm(im[newV], newV)
      } else {
        this.$set(this.webchat.peers, newV, this.monitorPeerNewIm(im[newV], newV))
      }
      bus.$emit('monitor:agentChangeIm', newV)
    },
    heartBeat(newV) {
      if (this.agentType === 'agent') {
        return
      }
      let y = parseInt(newV.incomingData.split(':')[1])
      // 当前呼入数
      this.summaryCall.incomingData = y
      // this.summaryCall.queueData = newV.queueData
    }
  },
  provide() {
    let user = this.$store.state.session.user || {}
    let show = user.type === 'admin' ? true : !isHasMenu('func_forbid_config_header_monitor', user)
    return {
      phoneServiceNums: this.phone.serviceNums,
      phonePeers: this.phone.peers,
      phoneQueues: this.phone.queues,
      webchatPeers: this.webchat.peers,
      summary: this.summaryCall,
      commonData: this.commonData,
      init: this.init,
      initWebchat: this.webchatInit,
      licenceType: this.licenceType,
      agentType: this.agentType,
      configHeaderShow: show
    }
  },
  beforeRouteLeave(to, from, next) {
    this.currentRoute = from.fullPath
    next()
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (vm.currentRoute) {
        vm.$router.push({ path: vm.currentRoute })
      }
    })
  },
  beforeMount() {
    this.initData()
    if (isHasMenu('monitor_summary', this.$store.state.session.user)) {
      this.monitorSummaryShow = true
    } else {
      this.monitorSummaryShow = false
    }
    this.$store.commit('monitor/MONITOR_MODULE_OPEN', { type: 'newCall', status: true })
    let p4 = this.$store.dispatch('getCache', { type: 'agents' })
    Promise.all([p4]).then(([p4]) => {
      this.loading = false
      if (this.flag === 'kf') {
        if (this.monitorSummaryShow) {
          // 有权限，就展示电话监控概览
          this.activeComponent = 'CallSummary'
        } else {
          // 没有权限，就展示电话监控详情
          this.activeComponent = 'MonitorTable'
        }
      } else {
        this.activeComponent = 'WebchatSummary'
      }
      // this.activeComponent = 'CallSummary'
      this.timeChange()
    })
  }
}
</script>
<style lang="stylus">
@import '../../../assets/common.styl';
  .monitor-table
    .el-table
      td
        padding 9px 10px
  .monitor-agent-tooltip.el-tooltip__popper.is-light
    border 1px solid #eee
/*  .monitor
    .el-submenu
      .el-menu-item
        padding-left 20px !important
        min-width 152px !important
        color $cf-gray4
        line-height 32px
        height 32px
      .el-submenu__title
        color $cf-gray1
        font-weight bold
        line-height 42px
        font-size 14px
        height 42px
    .el-menu-item
      color $cf-gray1
      font-weight bold
      line-height 42px
      font-size 14px
      height 42px
      &:hover
        background-color #dddee0 !important
    .el-menu-item.is-active
      color $c-main
      background-color #dddee0 !important*/
</style>
<style lang="stylus" scoped>
@import '../../../assets/common.styl';
.monitor
  height calc(100vh - 53px)
  padding-top 2px
  .left_list
    width 150px
    height 100%
    background #f0f2f3
    box-shadow 0px 0px 6px rgba(0,0,0,0.1)
    border-right 1px solid #e0e0e0
    overflow hidden
    overflow-y auto
    li
      margin-top 20px
      h3
        width 130px
        padding-left 20px
        color #000
        font-weight bold
        line-height 30px
      .title-hover
        &:hover
          background #e1e3e5
          color #000
          cursor pointer
      p
        width 130px
        line-height 30px
        padding-left 20px
        font-size 14px
        color #424242
        cursor pointer
        overflow hidden
        text-overflow ellipsis
        white-space nowrap
        &:hover
          background #e1e3e5
          color #000
      .active
        background #dcdee0
        color #459ae9
  .summary
    height calc(100vh - 53px)
    width calc(100% - 100px)
    background $cf-white
    overflow-y auto
.loading
  height: 100vh
.el-tabs__item
  margin-left: 12px
</style>
